#!/usr/bin/python
import time
import json
import urllib2
import urllib
import urlparse
import re
LOCAL = False
try:
	from google.appengine.api import rdbms
except:
	print "local version"
	LOCAL = True

_INSTANCE_NAME='dublin-nightsdb:instance1'

START_TIME = int(time.time() - 86400)

APP_ID = '168362376621089'
APP_SECRET = 'e01aac64b2192d0033679ccb7426269d'
TOKEN = 'AAACEdEose0cBABnd2FfwQ6tWNdSCXryr8MiGmXvLPCMcHZCT9p2bZAteUwvJjjyFq5ZBjWcurT8C8fiuxbxbSB96yPCXAGR0K0qfP1VsbEVe3dOIHSQ' 
TOKEN =  'access_token=' + TOKEN
 
def get_event_details(event_id):
	# get token
	# resp = urllib2.urlopen('https://graph.facebook.com/oauth/access_token?client_id='+APP_ID+'&client_secret='+APP_SECRET+'&grant_type=client_credentials')
	# token = resp.read()

	#get page
	resp = urllib2.urlopen('https://graph.facebook.com/'+str(event_id)+'?'+TOKEN)
	result = json.loads(resp.read())
	resp = urllib2.urlopen('https://graph.facebook.com/'+str(event_id)+'/picture?type=normal&redirect=false&'+TOKEN)	
	picurl = json.loads(resp.read())
	result['picurl'] = picurl['data']['url']
	return result


def get_events(uid):
#	QUERY = "SELECT eid FROM event WHERE creator = "+str(uid)+" AND eid IN (SELECT eid FROM event_member WHERE uid = "+str(uid)+") AND start_time > "+str(START_TIME)+" ORDER BY start_time"
	QUERY = "SELECT eid FROM event WHERE creator = "+str(uid)+" AND eid IN (SELECT eid FROM event_member WHERE uid = "+str(uid)+") "

	# get token
	#	resp = urllib2.urlopen('https://graph.facebook.com/oauth/access_token?client_id='+APP_ID+'&client_secret='+APP_SECRET+'&grant_type=client_credentials')
	#	token = resp.read()
	#	token = 'access_token=AAACEdEose0cBALabDR1qdt49zrN5UqVvvL4ZB15kkkKY1nfsvxGPTvhgqO8w1Qv1F1dSrTJZAf2Qw5FhCTZA2x6AxzuS1zSZCrH5vzoIRhoEbhKZCnCZBR'

    # get events
	url = 'https://graph.facebook.com/fql?q='+QUERY+'&'+TOKEN

	#remove duplicate spaces
	formattedurl = re.sub(' +',' ', url)
	formattedurl = re.sub(' ','%20', formattedurl)
	resp = urllib2.urlopen(formattedurl)
	result = json.loads(resp.read())['data']
	resp = urllib2.urlopen('https://graph.facebook.com/'+str(uid)+'/picture?type=normal&redirect=false&'+TOKEN)	
	picurl = json.loads(resp.read())
	new_result = []
	for event_id in result:
		event_id['url'] = str(picurl['data']['url'])
		new_result.append(event_id)
	return new_result		

events = []
events.append(get_events(129868223697316)) # Button factory
events.append(get_events(123984920950818)) # twisted pepper
events.append(get_events(153162514721751)) # Coppers
events.append(get_events(112813520933)) # the accademy
events.append(get_events(157563624278622)) # Tripod
events.append(get_events(126593817395840)) # Diceys

events.append(get_events(100451590001204)) # vanilla
events.append(get_events(18662177879	  ))  # dtwo
events.append(get_events(345886548764988)) # parker browns
events.append(get_events(183549388358662)) # kitchen
events.append(get_events(554513324565488)) # everliegh
events.append(get_events(119532114788607)) # glitz
events.append(get_events(100004270321502)) # heartbreakers
events.append(get_events(100002508069951)) # junior spesh
events.append(get_events(100001521505789)) # workmans
events.append(get_events(150619634969112)) # grand social

#f = open('clubs.txt', 'w')
#f.write(events)
#f.close
events = sum(events,[])
queries = []
# process each event
for event_id in events:
	
	event =  get_event_details(event_id['eid'])
	eventID = event['id']		
	clubID = event['owner']['id']
	clubName = event['owner']['name']
	age = 18
	entryPrice = -1
	vip = 1 if event['description'].find("VIP") > 0 else 0
	date, startTime = event['start_time'].split("T")
	drinkspromos = "<blank>"
	promoted = 0
	EventPicURL = event['picurl']# 'https://graph.facebook.com/'+str(event_id['eid'])+'/picture?type=square'
	ClubPicURL = event_id['url']
	eventDescription = event['description']
	location = event['location']
	eventName = event['name']
	eventLink = 'https://www.facebook.com/events/'+ event['id']
	clubQuery = """INSERT IGNORE INTO clubs VALUES (%d, '%s', '%s', %d, '%s', '%s')""" % (int(clubID) , clubName, location, 0, 'email@example.com', ClubPicURL)
	eventQuery = """REPLACE INTO events VALUES (%d, %d, %d, %d, %d, '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s')""" % (int(eventID), int(clubID), age, entryPrice, vip, str(startTime), str(date), drinkspromos, promoted, EventPicURL, eventDescription.replace("'", '').encode('unicode-escape'), location, eventName.replace("'", '').encode('unicode-escape'), eventLink, time.asctime(time.strptime(str(date), '%Y-%m-%d')).split(' ')[0])

	queries.append((clubQuery,eventQuery))

	#print event['owner']['name'], ":", event['name'] 
	print "-----------------------------------------"

# fill database
if LOCAL == False:
	conn = rdbms.connect(instance=_INSTANCE_NAME, database="mysql")
	c = conn.cursor()
	


	for query in queries:
		c.execute(query[0])
		c.execute(query[1])
	
	conn.commit()
	conn.close()
